package com.simpleactors;

/**
 * @author Dmitry
 */
public class RoundRobinActor extends MultipleActorsWrapper {
    private volatile int roundRobinIndex = 0;

    public RoundRobinActor(String name, Actor... actors) {
        super(name, actors);
    }

    @Override
    public boolean send(Object value, Actor sender) {
        if (size == 0) {
            throw new IllegalStateException("RoundRobinActor does not contain any actors inside");
        }
        lock.lock();
        try {
            Actor actor = actors[roundRobinIndex];
            roundRobinIndex++;
            if (roundRobinIndex >= size) {
                roundRobinIndex = 0;
            }
            return actor.send(value, sender);
        } finally {
            lock.unlock();
        }
    }
}
